package com.deyuanyun.pic.settings.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.deyuanyun.pic.common.security.rsa.KeyFormat;
import com.deyuanyun.pic.common.security.rsa.KeyWorker;
import com.deyuanyun.pic.common.util.ApplicationConfigUtil;
import com.deyuanyun.pic.common.util.CommonUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.settings.domain.base.Code;
import com.deyuanyun.pic.settings.domain.greatwall.LogUserExpand;
import com.deyuanyun.pic.settings.domain.greatwall.ProductLogExpand;
import com.deyuanyun.pic.settings.domain.greatwall.ProductLogTempExpand;
import com.deyuanyun.pic.settings.domain.greatwall.ProductLogTempWithBLOBs;
import com.deyuanyun.pic.settings.service.base.CodeService;
import com.deyuanyun.pic.settings.service.greatwall.LogUserService;
import com.deyuanyun.pic.settings.service.greatwall.ProductLogService;
import com.deyuanyun.pic.settings.service.greatwall.ProductLogTempService;
import com.github.pagehelper.Page;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chace.cai   xu
 * @description
 * 定时任务入口
 * @date 2016/4/13
 */
@Component
public class MainTask {
    static Logger logger = Logger.getLogger(MainTask.class);

    public static Map<String, Date> taskRunTime = new HashMap<String, Date>();//每增加一组任务。该值加

    @Scheduled(cron="0 0/2 *  * * ?")
    public void taskMainMethod(){
        String isRun= ApplicationConfigUtil.getConfigByName("IS_RUN_TASK");
        if (!"true".equalsIgnoreCase(isRun)){
            return;
        }
    }

    @Autowired
    private LogUserService logUserService;

    @Autowired
    private ProductLogService productLogService;

    @Autowired
    private ProductLogTempService productLogTempService;

    @Autowired
    private CodeService codeService;

    /**
     * 日志信息发送task
     * @param
     * @return 
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-12-26
     */
   /* @Scheduled(cron="0 0 0 7 * ? ")*/
    public void taskGMethod(){
        try {
            String ip = ApplicationConfigUtil.getConfigByName("gwServiveIp");
            String sn = "123"; //todo axiao 序列号暂定
            if(StringUtils.isNotEmpty(ip)) {
                Code code = codeService.getGwNCode(sn, "GW_K_TYPE_B");
                String publicKey = code.getCreateRemark();
                if(StringUtils.isNotEmpty(publicKey)) {
                    KeyWorker publicWorker =  new KeyWorker(publicKey, KeyFormat.ASN);
                    Page<LogUserExpand> expands = logUserService.queryUntreatedLogs(1, 30);
                    for (LogUserExpand expand : expands) {
                        List<ProductLogExpand> logExpands = expand.getProductLogs();
                        for (ProductLogExpand logExpand : logExpands) {
                            productLogService.updateHandleData(logExpand.getId());
                        }
                        ProductLogTempWithBLOBs productLogTemp = new ProductLogTempExpand();
                        productLogTemp.setId(CommonUtil.getUUID());
                        productLogTemp.setCreateDate(expand.getCreateDate());
                        productLogTemp.setSn(sn);
                        String cText = publicWorker.encrypt(JSON.toJSONString(expand)); //RSA加密后的数据
                        String mText = DigestUtils.md5Hex(cText); //RSA加密后的数据再MD5加密的值
                        productLogTemp.setcText(cText);
                        productLogTemp.setmText(mText);
                        productLogTemp.setPkText(publicKey);
                        productLogTempService.insertSelective(productLogTemp);
                    }
                }
                List<String> strList = new ArrayList<String>();
                Page<ProductLogTempExpand> tempExpands = productLogTempService.queryUntreatedLogs(1, 30);
                for (ProductLogTempExpand tempExpand : tempExpands) {
                    strList.add(tempExpand.getId());
                }

                CloseableHttpClient httpclient = HttpClients.createDefault();
                HttpPost httpPost = new HttpPost(ip + "/h/d.json");
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("list", (List)tempExpands);
                //发送json格式的数据
                StringEntity myEntity = new StringEntity(JSON.toJSONString(map),
                        ContentType.create(FastJsonJsonView.DEFAULT_CONTENT_TYPE, FastJsonJsonView.UTF8));
                httpPost.setEntity(myEntity);

                ResponseHandler<JSONObject> responseHandler = new ResponseHandler<JSONObject>() {
                    @Override
                    public JSONObject handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                        int status = response.getStatusLine().getStatusCode();
                        if(status == 200) {
                            HttpEntity httpEntity = response.getEntity();
                            if(null != httpEntity) {
                                String result = EntityUtils.toString(httpEntity);
                                //根据字符串生成JSON对象
                                JSONObject resultObj = JSONObject.parseObject(result);
                                return resultObj;
                            } else {
                                return null;
                            }
                        }
                        else {
                            throw new ClientProtocolException("Unexpected response status: " + status);
                        }
                    }
                };
                JSONObject jsonObject = httpclient.execute(httpPost, responseHandler);
                System.out.println(jsonObject);
                String resultCode = jsonObject.getString("code");
                if("0000".equals(resultCode)) {
                    logger.info("处理成功！");
                } else {
                    productLogTempService.updateHandleByIds(strList);
                    logger.info("已经处理：" + strList.toString());
                }
            }
        } catch (ClientProtocolException e) {
            logger.error(e.getMessage(), e);
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
